package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gopkg.in/olahol/melody.v1"
)

func webUpdateUinfo(c *gin.Context) {
	deviceID := c.Query("device_id")
	pName := c.Query("p_name")
	loginStatus := c.Query("login_status")
	loginName := c.Query("login_name")
	follow := c.Query("follow")
	fans := c.Query("fans")
	updateUinfo(deviceID, pName, loginStatus, loginName, follow, fans)
	c.String(http.StatusOK, "ok")
}

func webTaskAdd(c *gin.Context) {
	deviceID := c.Query("device_id")
	pName := c.Query("p_name")
	tType := c.Query("t_type")
	extra := c.Query("extra")

	taskAdd(deviceID, pName, tType, extra)
	c.String(http.StatusOK, "ok")
}

func webJobAdd(c *gin.Context) {
	devices := c.Query("devices")
	jType := c.Query("type")
	jobAdd(devices, jType)
	c.String(http.StatusOK, "ok")
}

func initWeb() {
	router := gin.Default()
	mrouter := melody.New()

	router.GET("/ws", func(c *gin.Context) {
		mrouter.HandleRequest(c.Writer, c.Request)
	})
	mrouter.HandleMessage(handmessage)

	router.GET("/userinfo", webUpdateUinfo)
	router.GET("/task/add", webTaskAdd)
	router.GET("/job/add", webJobAdd)
	router.GET("/job/restart", func(c *gin.Context) {
		go monitor.restartDevices()
		c.String(http.StatusOK, "ok")
	})

	router.Static("/assets", "./assets")
	router.Run(":7788")
}
